#ifndef _GC_COMMON_SAVE_CONFIG_H_
#define _GC_COMMON_SAVE_CONIFG_H_

#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <libgen.h>
#include <errno.h>
#include <json/json.h>
#include "get_config_by_file.h"


int gc_save_config_to_cache(const gc_config_t * config, const gc_list_t * list) {
	if(config->cache_file == NULL) {
		fprintf(stderr, "%s:%d: gc_config_t::cache_file is empty!\n", __FILE__, __LINE__);
		return -1;
	}

	json_object * json = gc_convert_list_to_json_object(list);

	struct stat st;

	char dir[1024] = {0}, *path = dir;
	memcpy(path, config->cache_file, strlen(config->cache_file) + 1);
	path = dirname(path);

	errno = 0;
	if(stat(path, &st) == -1) {
		if(errno == ENOENT) {
			errno = 0;
			if(mkdir(path, 0755) == -1) {
				fprintf(stderr, "%s:%d: create dir %s failed: %s\n", 
						__FILE__, __LINE__, path, strerror(errno));
				json_object_put(json);
				return -1;
			}
		} else {
			fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, strerror(errno));	
			json_object_put(json);
			return -1;
		}
	}
	

	int ret = json_object_to_file(config->cache_file, json);

	json_object_put(json);

	return ret;
}

gc_list_t * gc_load_config_from_cache(const gc_config_t * config) {

	if(config->cache_file == NULL) {
		fprintf(stderr, "%s:%d: gc_config_t::cache_file is empty!\n", __FILE__, __LINE__);
		return NULL;    
	}   

	json_object * json = json_object_from_file(config->cache_file);

	gc_list_t * list = gc_convert_json_object_to_list(json);

	if(json != NULL) {
		json_object_put(json);
	}   

	return list;
}
#endif
